package de.IIIfeed.MoneyPlanner;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.technologichron.manacalc.FloatPicker;

import org.kroz.activerecord.ActiveRecordException;
import org.kroz.activerecord.Database;
import org.kroz.activerecord.DatabaseBuilder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Manage extends Activity {
	MyAdapter adapter;
	protected static Item item;
	ListView table;
	List<Item> items;
	
	protected class MyAdapter extends BaseAdapter {
		List<Item> data;
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		public MyAdapter(List<Item> _data){
			data = _data;
		}
		@Override
		public boolean areAllItemsEnabled() {
			return false; //the first is the header
		}

		@Override
		public boolean isEnabled(int position) {
			return position == 0 ? false : true;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Item getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return getItem(position).id;
		}
		@Override
		public boolean isEmpty() {
			// TODO Auto-generated method stub
			return data.isEmpty();
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null ){
				convertView = vi.inflate(R.layout.manage_item, null);
			} 
			TextView title = (TextView) convertView.findViewById(R.id.title);
			TextView time = (TextView) convertView.findViewById(R.id.time);
			TextView amount = (TextView) convertView.findViewById(R.id.amount);
			TextView currency = (TextView) convertView.findViewById(R.id.currency);
			
			Item item = getItem(position);
			
			title.setText(item.title);
			amount.setText(String.valueOf(item.amount));
			
			StringBuilder timeStr = new StringBuilder();
			switch (item.type) {
			case MoneyPlanner.ONCE:
				timeStr.append(getString(R.string.once)+" ");
				timeStr.append(getString(R.string.on)+ " ");
				timeStr.append(new SimpleDateFormat("MMMM d. yyyy").format(item.dateStart));
				break;
			default:
				timeStr.append(getString(R.string.periodically)+": ");
				if(item.repeatType == MoneyPlanner.DAILY){
					timeStr.append(getString(R.string.daily));
				} else if(item.repeatType == MoneyPlanner.WEEKLY){
					timeStr.append(getString(R.string.weekly));
					timeStr.append(new SimpleDateFormat("EEEE").format(item.dateStart));
				} else if(item.repeatType == MoneyPlanner.MONTHLY){
					timeStr.append(getString(R.string.monthly));
					timeStr.append(new SimpleDateFormat("d.").format(item.dateStart));
				} else if(item.repeatType == MoneyPlanner.YEARLY){
					timeStr.append(getString(R.string.yearly));
					timeStr.append(new SimpleDateFormat("MMMM d").format(item.dateStart));
				} 
				if(item.repeatEnd != null){
					timeStr.append(getString(R.string.until)+" ");
					timeStr.append( DateFormat.getDateInstance(
				            DateFormat.MEDIUM).format(item.repeatEnd));
				}
				break;
			}
			time.setText(timeStr.toString());
			
			SharedPreferences mPrefs = getSharedPreferences("MoneyPlannerPrefs", 0); 
		    String c = mPrefs.getString("currency", "$");
		      
			currency.setText(c);
			
            return convertView;
		}

	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage);
        FloatPicker b = (net.technologichron.manacalc.FloatPicker) findViewById(R.id.initialAmount);
        SharedPreferences mPrefs = getSharedPreferences("MoneyPlannerPrefs", 0); 
        float initialAmount = mPrefs.getFloat("initialAmount", 0F);
        b.setValue(initialAmount);

        DatabaseBuilder builder = new DatabaseBuilder("MoneyPlanner");
        builder.addClass(Item.class);
        Database.setBuilder(builder);

        items = new ArrayList<Item>(); //empty, will be filled in onResume
        table = (ListView) findViewById(R.id.items);
        adapter = new MyAdapter(items); 
        table.setAdapter(adapter);
        
        table.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Item item = adapter.getItem(arg2);
				Intent intent = new Intent(Manage.this, AddAndUpdate.class);
				intent.putExtra("caller", ".ShowItems");
				Manage.item = item;
				startActivity(intent);
			}
		});

        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences mPrefs = getSharedPreferences("MoneyPlannerPrefs", 0); 
				SharedPreferences.Editor ed = mPrefs.edit();
				
				net.technologichron.manacalc.FloatPicker picker = (net.technologichron.manacalc.FloatPicker) findViewById(R.id.initialAmount);
				
				ed.putFloat("initialAmount", picker.getValue());
				ed.putString("initialTime", new Date().toString());
				ed.commit();
			}
		});
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	items.clear();
    	try {
			items.addAll(MoneyPlanner.db.findAll(Item.class));
		} catch (ActiveRecordException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			adapter.notifyDataSetChanged();
			adapter.notifyDataSetInvalidated();
		}
    	
    }
}